google.load("feeds", "1");

var feed_last_update = function(name, update) {

    /* Function to use the found feed. */
    var use_feed = function(result) {
        var status; 

        if (result.error) {
            status = "ERROR " + result.error.message;
        }
        else {
            var entries = result.feed.entries;
            var latest_date = new Date(1900, 1, 1);

            /* Need to find the latest date manually. */
            for (x=0; x < entries.length; x+=1) {
                var entry_date = new Date(entries[x].publishedDate);
                if (entry_date > latest_date)
                    latest_date = entry_date;
            }
            var date_str = latest_date.getFullYear() + "-" +
                pad_two_digits(latest_date.getMonth() + 1) +
                "-" + pad_two_digits(latest_date.getDate());

            status = "(last update: " + date_str + ")";
        }
        $(update).text(status).fadeIn();
    }

    /* Find the feed for the specified web page. */
    var found_feed = function(result) {
        if (result.error) {
            $(update).text("ERROR " + result.error.message);
        }
        else {
            var feed = new google.feeds.Feed(result.url, use_feed);
            feed.load(use_feed);
        }
    }

    var url = $("a:contains('"+name+"')").attr("href");
    google.feeds.lookupFeed(url, found_feed);
}

var pad_two_digits = function(num) {
    var num_str = num.toString();
    if (num_str.length == 1) {
        return "0" + num_str;
    }
    else {
        return num_str;
    }
}

var home_initialize = function () {
    feed_last_update("Askewed Thoughts", "#AT-updated");
    feed_last_update("Coder Who Says Py", "#py-updated");
}

google.setOnLoadCallback(home_initialize);

